package com.zx._09_架构.load_balance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.stream.Collectors;

public class LB0_common {

    private static final List<String> SERVERS = new ArrayList<String>();

    private static final Map<String, Integer> SERVER_WEIGHT = new HashMap<>();

    private static final List<String> SELECTER_RESULT = new ArrayList<>();

    /**
     * 模拟随机参数
     */
    private static final Random paramRandom = new Random();

    static {
        // 服务列表
        SERVERS.add("A");
        SERVERS.add("B");
        SERVERS.add("C");

        // 加权的服务列表
        SERVER_WEIGHT.put("A", 5);
        SERVER_WEIGHT.put("B", 1);
        SERVER_WEIGHT.put("C", 2);
    }

    public static List<String> getServers() {
        return LB0_common.SERVERS;
    }

    public static Map<String, Integer> getWeightServer() {
        return LB0_common.SERVER_WEIGHT;
    }


    public static void saveResult(String server) {
        SELECTER_RESULT.add(server);
    }

    public static void printResultAndClear() {
        Map<String, List<String>> resMap =
                LB0_common.SELECTER_RESULT.stream().collect(Collectors.groupingBy(x -> x));

        int sum = LB0_common.SELECTER_RESULT.size();

        System.out.println("######  printResultAndClear begin ######");
        for (Entry<String, List<String>> entry : resMap.entrySet()) {

            double p = entry.getValue().size() * 100.0d / sum;
            System.out.println(entry.getKey() + "=" + p);
        }
        System.out.println("######  printResultAndClear end  ######");
        SELECTER_RESULT.clear();
    }

    /**
     * 生产随机请求参数
     *
     * @return
     */
    static String getParams() {
        return "" + paramRandom.nextInt(10000);
    }

}
